package com.ziytek.web.citizen.service;

import com.ziytek.web.citizen.config.ConfigInit;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.event.BasicDataEvent;
import com.ziytek.web.citizen.event.CommandResponseEvent;
import com.ziytek.web.citizen.event.DeviceRequestEvent;
import com.ziytek.web.citizen.event.RealDataEvent;
import com.ziytek.web.citizen.model.bean.DeviceRequestModel;
import com.ziytek.web.citizen.model.data.CommandResponse;
import com.ziytek.web.citizen.model.data.RealData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * TCP接受数据处理
 *
 * @author fenghx
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ChannelReadService {
    private final ConfigInit configInit;
    private final ApplicationContext context;

    public void channelRead(Object msg) {
        switch (msg) {
            case RealData rd:
                log.info("周期数据解析成功,发布事件");
                context.publishEvent(new BasicDataEvent(rd));
                context.publishEvent(new RealDataEvent(rd));
                return;
            case CommandResponse cr:
                if (NumConstant.INT_ZERO == cr.getS()) {
                    log.info("指令响应数据解析失败,发布事件");
                    return;
                }

                log.info("指令响应数据解析成功,发布事件");
                context.publishEvent(new CommandResponseEvent(cr));
                return;
            case DeviceRequestModel dr:
                if (Integer.parseInt(ServerConstant.CMD_TYPE_BUSINESS_REQUEST) == dr.getT()) {
                    log.info("设备断开重连请求业务,发布事件");
                    if (configInit.isInterruptAutomatic()) {
                        context.publishEvent(new DeviceRequestEvent(dr));
                    }
                }
                return;
            default:
                log.info("channelRead Unexpected value: {}", msg);
        }
    }
}
